<?php
require_once 'CMS/Util.php';
require_once 'CMS/Mvc/BaseController.php';
require_once 'CMS/Mvc/BaseUserController.php';
require_once 'CMS/UserCommon.php';
require_once 'CMS/User.php';
require_once 'CMS/Language.php'; //include thu vien language

//Người tạo	: Bùi Thành Nguyên - Team 4
//Module 	: Shopping Cart
//Chức năng	: Show giỏ hàng
 
class CartController extends BaseUserController{

	public function init(){
		parent::init();
		$tbSetting = new User_Model_Parameter();
		$temp = $tbSetting->selectSetting("config");
		$layout = unserialize($temp[0]["parameter_value"]);
		if($layout['config_template'] !="")
		{
			$this->_helper->layout()->setLayout($layout['config_template']);
			$_SESSION['config_template'] = $layout['config_template'];
		}
		else
		{
			$this->_helper->layout()->setLayout('layoutmain');
			$_SESSION['config_template'] = 'layoutmain';
		}
	}

	//indexAction thực hiện show giỏ hàng
	public function indexAction(){
		$_SESSION['page_code'] = 'cart';
		$language = new Language(APPLICATION_PATH . '/modules/user/languages/cart');
			if(isset($_SESSION['language']))
			{
				$language_id = $_SESSION['language'];
				$tbLanguage = new Language_Model_Language();
				$name = $tbLanguage->getNameLanguage($language_id);
				$language->load($name['name']);
			}
			else
				$language->load('Default');		
				
			$languages = $tbLanguage->getAllLanguages();
			$this->view->languages = $languages;
			/*========== End Load Language ==========*/
				
			/*========== Start Get Text ==============*/
			$this->view->text_title 	= $language->get('text_title');
			$this->view->text_no 		= $language->get('text_no');
			$this->view->text_name 		= $language->get('text_name');
			$this->view->text_total		= $language->get('text_total');
			$this->view->text_quan		= $language->get('text_quan');
			$this->view->text_act		= $language->get('text_act');
			$this->view->text_price		= $language->get('text_price');
			$this->view->text_lang 		= $language->get('text_lang');
			$this->view->text_subtotal 	= $language->get('text_subtotal');
			$this->view->text_del 		= $language->get('text_del');
			$this->view->text_recal		= $language->get('text_recal');
			$this->view->text_check 	= $language->get('text_check');
			$this->view->text_empty		= $language->get('text_empty');
			$this->view->text_image		= $language->get('text_image');
			$this->view->confirm		= $language->get('confirm');
			
			/*========== End Text ==============*/		
		
		$tbSidebarModule = new User_Model_SidebarModule();
		$Modules = $tbSidebarModule->selectAllModule();
		foreach($Modules as $module)
		{
			$database_show_widget [] = $module["module_code"];
			$database_order_widget [$module["module_code"]] =  $module["sort_order"];
		}
		
		$tbDefaultbarModule = new User_Model_DefaultModuleToPage();
		$defaultModules = $tbDefaultbarModule->selectAllModule("cart");
		if($defaultModules!=null)
		{
			foreach($defaultModules as $dmodule)
			{
				$content_show_widget [] = $dmodule["module_code"];
				$content_order_widget [$dmodule["module_code"]] =  $dmodule["sort_order"];
			}
		}
		$tbContentbarModule = new User_Model_ContentModuleToPage();
		// mac dinh homepage
		$ContentModules = $tbContentbarModule->selectAllModule("cart");	
		if($ContentModules!=null)
		{
			foreach($ContentModules as $cmodule)
			{
				$content_show_widget [] = $cmodule["module_code"];
				$content_order_widget [$cmodule["module_code"]] =  $cmodule["sort_order"];
			}	
		}
		$front     = Zend_Controller_Front::getInstance();
		$widgets = $front->getPlugins();
	
		foreach($widgets as $widget)
		{
			if(count($Modules) > 0){
				if($widget->name !="" && in_array($widget->name, $database_show_widget))
				{
					$widget->enable = 1;
					$widget->order = $database_order_widget[$widget->name];
				}
			}
			if(count($content_show_widget) > 0){
				if($widget->name !="" && in_array($widget->name, $content_show_widget))
				{
						$widget->enable = 1;
						$widget->order = $content_order_widget[$widget->name];
				}	
			}	
		}
		
		
		//Start------Check Input Parameter
		//End--------Check Input Parameter
		
		//Start------Khai báo các parameter
		$tbCategories = new User_Model_Categories();
		$tbThings= new User_Model_Things();
		//End--------Khai báo các parameter
		
		//Start------Get Categories
		$AllCategories = $tbCategories->getAllCategories();
		//End--------Get Categories
		
		//Start------Get Products
		$Products= $tbThings->getAllThingsbyType(1);
		//End--------Get Products
		
		//Start------Xử lý tính lại theo số lượng bao gồm xóa sản phẩm
		if(count($_POST))
		{
			if(is_array($_POST["quantity"]))
			{
				foreach($_POST["quantity"] as $id=>$qty)
				{
					if(is_numeric($qty) && $qty==0)//Nếu số lượng là 0 thì xóa khỏi giỏ hàng
					{
						unset($_SESSION["Cart"][$id]);
					}
					else if(is_numeric($qty) && $qty>=1)//Nếu số lượng lớn hơn bằng 1 thì cập nhật lại session
					{
						$_SESSION["Cart"][$id]=$qty;
					}
				}
			}
		}
		//End--------Xử lý tính lại theo số lượng
		
		//Start------Truyền parameter qua View
		$this->view->AllCategories = $AllCategories;
		$this->view->Products=$Products;
		if(isset($_SESSION["Cart"]))
		{
			$Exist=0;
			foreach ($_SESSION["Cart"] as $id=>$qty)
			{
				if(isset($id))
				{
					$Exist=1;
					break;
				}
			}
			if($Exist==0)
				$this->view->cart=0;
			else
				$this->view->cart=$_SESSION["Cart"];
		}
		else
		{
			$this->view->cart=0;
		}
		//End--------Truyền parameter qua View
		if(isset($_GET['payment']) && $_GET['payment']==1 )
		{
			Header("Location: /cart/payment?step=1");
		}
		
	}
	
	public function paymentAction(){
		$session = new Zend_Session_Namespace('login.auth');
		
		$language = new Language(APPLICATION_PATH . '/modules/user/languages/cart');
			if(isset($_SESSION['language']))
			{
				$language_id = $_SESSION['language'];
				$tbLanguage = new Language_Model_Language();
				$name = $tbLanguage->getNameLanguage($language_id);
				$language->load($name['name']);
			}
			else
				$language->load('Default');		
				
			$languages = $tbLanguage->getAllLanguages();
			$this->view->languages = $languages;
			/*========== End Load Language ==========*/
				
			/*========== Start Get Text ==============*/
			$this->view->text_title 	= $language->get('text_title');
			$this->view->text_no 		= $language->get('text_no');
			$this->view->text_name 		= $language->get('text_name');
			$this->view->text_total		= $language->get('text_total');
			$this->view->text_quan		= $language->get('text_quan');
			$this->view->text_act		= $language->get('text_act');
			$this->view->text_price		= $language->get('text_price');
			$this->view->text_lang 		= $language->get('text_lang');
			$this->view->text_arrCtrlLang = $language->get('text_arrCtrlLang');
			
			$this->view->text_subtotal 	= $language->get('text_subtotal');
			$this->view->text_del 		= $language->get('text_del');
			$this->view->text_recal		= $language->get('text_recal');
			$this->view->text_check 	= $language->get('text_check');
			$this->view->text_empty		= $language->get('text_empty');
			$this->view->text_image		= $language->get('text_image');
			$this->view->confirm		= $language->get('confirm');
			
			
			
			$this->view->check_out_1		= $language->get('check_out_1');
			$this->view->check_out_2		= $language->get('check_out_2');
			$this->view->check_1_label1		= $language->get('check_1_label1');
			$this->view->check_1_label2		= $language->get('check_1_label2');
			$this->view->check_1_require	= $language->get('check_1_require');
			$this->view->check_1_order		= $language->get('check_1_order');
			$this->view->check_1_receiver	= $language->get('check_1_receiver');
			$this->view->check_1_transport	= $language->get('check_1_transport');
			$this->view->check_1_paymethod	= $language->get('check_1_paymethod');
			$this->view->check_name			= $language->get('check_name');
			$this->view->check_Sex			= $language->get('check_Sex');
			$this->view->check_phone		= $language->get('check_phone');
			$this->view->check_note			= $language->get('check_note');
			$this->view->check_1_re_time	= $language->get('check_1_re_time');
			$this->view->check_1_time_format= $language->get('check_1_time_format');
			$this->view->check_1_review		= $language->get('check_1_review');
			$this->view->check_1_btn		= $language->get('check_1_btn');
			$this->view->check_male		= $language->get('check_male');
			$this->view->check_female		= $language->get('check_female');
			$this->view->check_add		= $language->get('check_add');
			$this->view->check_same	= $language->get('check_same');
			$this->view->check_pay	= $language->get('check_pay');
			$this->view->order	= $language->get('order');
			$this->view->pay	= $language->get('pay');
			$this->view->trans	= $language->get('trans');
			$this->view->return	= $language->get('return');
			$this->view->change	= $language->get('change');
			$this->view->ok	= $language->get('ok');
			$this->view->skip	= $language->get('skip');
			
			
			
			
			
			
			/*========== End Text ==============*/		
		
		$_SESSION['page_code'] = 'cart';
		
		$tbSidebarModule = new User_Model_SidebarModule();
		$Modules = $tbSidebarModule->selectAllModule();
		if($Modules!=null)
		{
			foreach($Modules as $module)
			{
				$database_show_widget [] = $module["module_code"];
				$database_order_widget [$module["module_code"]] =  $module["sort_order"];
			}
		}
		$tbDefaultbarModule = new User_Model_DefaultModuleToPage();
		$defaultModules = $tbDefaultbarModule->selectAllModule("cart");
		if($defaultModules!=null)
		{
			foreach($defaultModules as $dmodule)
			{
				$content_show_widget [] = $dmodule["module_code"];
				$content_order_widget [$dmodule["module_code"]] =  $dmodule["sort_order"];
			}
		}
		$tbContentbarModule = new User_Model_ContentModuleToPage();
		// mac dinh homepage
		$ContentModules = $tbContentbarModule->selectAllModule("cart");	
		if($ContentModules!=null)
		{
			foreach($ContentModules as $cmodule)
			{
				$content_show_widget [] = $cmodule["module_code"];
				$content_order_widget [$cmodule["module_code"]] =  $cmodule["sort_order"];
			}	
		}
		$front     = Zend_Controller_Front::getInstance();
		$widgets = $front->getPlugins();
	
		foreach($widgets as $widget)
		{
			if(count($Modules) > 0){
				if($widget->name !="" && in_array($widget->name, $database_show_widget))
				{
					$widget->enable = 1;
					$widget->order = $database_order_widget[$widget->name];
				}
			}
			if(count($content_show_widget) > 0){
				if($widget->name !="" && in_array($widget->name, $content_show_widget))
				{
						$widget->enable = 1;
						$widget->order = $content_order_widget[$widget->name];
				}	
			}	
		}
		
		$dbUser = new User_Model_Users();
		$dbPayment = new User_Model_Payment();
		$dbShipping = new User_Model_ShippingMethod();
		
   
		/*-------- Start kiem tra login -------------*/
		 if(isset($session->id_user))// them zend session cho này nè
		{
			// lay thong tin cac payment ma gian hang ho tro
			$payment = $dbPayment->getAllPayment();
			$allpayment = array();
			foreach ($payment as $pay){
				$payname = unserialize($pay['payment_name']);
				if(isset($payname[$name['name']]) && isset($name)){
					$payment_name = $payname[$name['name']];
				}else{
					$payment_name = $payname['Default'];
				}
					$allpayment[] = array(
										'payment_id'	=>	$pay['payment_id'],
										'payment_name'	=>	$payment_name
									);
			}
			
			$this->view->payment = $allpayment;
			// lay thong tin cac shipping ma gian hang ho tro
			$shipping = $dbShipping->getAllShipping();
			$allshipping = array();
			foreach ($shipping as $ship){
				$shippingname = unserialize($ship['shipping_name']);
				if(isset($shippingname[$name['name']]) && isset($name)){
					$shipping_name =$shippingname[$name['name']];
				}else{
					$shipping_name = $shippingname['Default'];
				}
					$allshipping[] = array(
										'shipping_id'	=>	$ship['shipping_id'],
										'shipping_name'	=>	$shipping_name,
										'cost'			=>$ship['cost']
									);
			}
			$this->view->shipping = $allshipping;
			// kiem tra currentstep
			
		
			/*********** START  lay thong tin shopping cart****************/
			//Start--------Khai báo các parameter
			$tbThings= new User_Model_Things();
			//End--------Khai báo các parameter
						
			//Start------Get Products
			$Products= $tbThings->getAllThingsbyType(1);
			//End--------Get Products
			$this->view->Products=$Products;
			if(isset($_SESSION["Cart"]))
			{
				$Exist=0;
				foreach ($_SESSION["Cart"] as $id=>$qty)
				{
					if(isset($id))
					{
						$Exist=1;
						break;
					}
				}
				if($Exist==0)
					$this->view->cart=0;
				else
					$this->view->cart=$_SESSION["Cart"];
			}
			else
			{
				$this->view->cart=0;
			}
			/*********** End  lay thong tin shopping cart****************/
			
		// xu ly submit 
			if(isset($_POST) || isset($_GET['sendorder']) )
			{
				// xu ly add order vao database
				if(isset($_GET['sendorder']) && $_GET['sendorder']==1 )
				{
					// kiem tra session co ton tai
					if(isset($_SESSION['payment_info']) && $_SESSION['payment_info']!=null && isset($_SESSION['Cart']) && $_SESSION['Cart']!=null)
					{
						$dbBill = new User_Model_Bill();
						$dbShipping = new User_Model_ShippingDetail();
						$dbBillDetail = new User_Model_BillDetail();
						
						// luu tru thong tin ve shipping
						$shipping = array(
							"shipping_id" => $_SESSION['payment_info']['ship'],
							"user_receive" => $_SESSION['payment_info']['ord_sname'],
							"address" => $_SESSION['payment_info']['ord_saddress'],
							"phone" => $_SESSION['payment_info']['ord_sphone'],
							"email" => $_SESSION['payment_info']['ord_semail'],
							"yahoo" => $_SESSION['payment_info']['ord_syahoo'],
							"skype" => $_SESSION['payment_info']['ord_sskype'],
							"note" => $_SESSION['payment_info']['ord_snote'],
							"sex" => $_SESSION['payment_info']['ord_sgender'],
							"created_date" => time(),				
						);
				
						$shipping_detail = $dbShipping->insertShipping($shipping);
						
						// luu tru thong tin ve bill
						$data = array(
							"bill_code" =>'Buy'.time(),
							"user_id" =>$session->id_user,
							"payment_id" =>$_SESSION['payment_info']['pay'],
							"shipping_detail_id" =>$shipping_detail,
							"total_bill_price" =>$_SESSION['payment_info']['total_price'],
							"created_date" =>time(),
							"updated_date" =>time(),
							"status" =>0,
							"ship_time" => serialize($_SESSION['ship_time'])
						);
						
						$bill_id = $dbBill->insertBill($data);
						$count = 0;
						
						// thuc hien add bill_detal
						foreach($_SESSION['Cart'] as $id=>$qty)
						{
								$count++;
								$cartProduct=0;
								foreach($Products as $product)
								{
									if($product["thing_id"]==$id)
									{
										$cartProduct=$product;
										break;
									}
								}
									
								$bill_detail = array(
								"bill_id" =>$bill_id,
								"thing_id" =>$id,
								"quantity" =>$qty,
								"price" =>$cartProduct['price'],
								"total_price" =>$qty*$cartProduct['price'],	
							);
							// xoa session
						
							unset($_SESSION['payment_info']);
							unset($_SESSION['Cart']);
							
							$dbBillDetail->insertBillDetail($bill_detail);
						}
					
						
						
						$data=1;
						$this->_helper->json($data);
						
					}
					else
					{
						
						Header("Location: /cart/error");
					}
					
				}
				else 
				{
					// gan vao sesssion
					if($_POST!=null)
					{
						$_SESSION['payment_info'] = $_POST;
						//print_r($_POST);
						$time = array(
							'gio'=>$_SESSION['payment_info']['gio'],
							'phut'=>$_SESSION['payment_info']['phut'],
							'ngay'=>$_SESSION['payment_info']['ngay'],
							'thang'=>$_SESSION['payment_info']['thang'],
							'nam'=>$_SESSION['payment_info']['nam'],
						); 
						$_SESSION['ship_time'] = $time;
					}
				}
			}
			if(isset($_GET['step']) && is_numeric($_GET['step']) && $_GET['step']==1)
			{
					// kiem tra ton tai cart
					if(!isset($_SESSION['Cart']) || $_SESSION['Cart']==null)
					{
						unset($_SESSION['payment_info']);
						Header("Location: /cart/error");
					}
					// neu da thuc hien buoc 1
					if(isset($_SESSION['payment_info']) && $_SESSION['payment_info']!=null)
					{
						// thuc hien gan gia tri
						// mang luu thong tin user dat hang
						$order_user= array(
							'user_name'=>$_SESSION['payment_info']['ord_name'],
							'sex'=>$_SESSION['payment_info']['ord_gender'],
							'address'=>$_SESSION['payment_info']['ord_address'],
							'email'=>$_SESSION['payment_info']['ord_email'],
							'phone'=>$_SESSION['payment_info']['ord_phone'],
							'yahoo'=>$_SESSION['payment_info']['ord_yahoo'],
							'skype'=>$_SESSION['payment_info']['ord_skype'],
							'note'=>$_SESSION['payment_info']['ord_note'],
						);
						$this->view->order_user = $order_user;
						
						// thuc hien gan gia tri
						if($_SESSION['payment_info']['ord_sgender'] == "Male")
							$sgender = 1;
						 else 
							$sgender = 0;
						
						//mang luu thong tin user nhan hang
						$rec_user= array(
							'user_name'=>$_SESSION['payment_info']['ord_sname'],
							'sex'=>$sgender,
							'address'=>$_SESSION['payment_info']['ord_saddress'],
							'email'=>$_SESSION['payment_info']['ord_semail'],
							'phone'=>$_SESSION['payment_info']['ord_sphone'],
							'yahoo'=>$_SESSION['payment_info']['ord_syahoo'],
							'skype'=>$_SESSION['payment_info']['ord_sskype'],
							'note'=>$_SESSION['payment_info']['ord_snote'],
						);
						$this->view->currentrecieve = $rec_user;
						
						// current payment
						$this->view->currentpayment = $_SESSION['payment_info']['pay'];
						
						//current shipping
						$this->view->currentshipping = $_SESSION['payment_info']['ship']; 
						
						// mang luu thoi gian nhan hang
						$time = array(
							'gio'=>$_SESSION['payment_info']['gio'],
							'phut'=>$_SESSION['payment_info']['phut'],
							'ngay'=>$_SESSION['payment_info']['ngay'],
							'thang'=>$_SESSION['payment_info']['thang'],
							'nam'=>$_SESSION['payment_info']['nam'],
						); 
						$_SESSION['ship_time'] = $time;
						$this->view->currenttime = $time;
					}
					else // chua thuc hien buoc 1 
					{
						
						// lay thong tin user đa dang nhap
						$user_info= $dbUser->selectUserInfoByUserID($session->id_user);
						$this->view->order_user = $user_info;
						
						// gan mac dinh current là phan tu dau tien
						$this->view->currentpayment = $payment[0]['payment_id'];
						$this->view->currentshipping = $shipping[0]['shipping_id']; 
						
						// gan mac dinh current time la thoi gian hien tại
						$time = array(
							'gio'=>"",
							'phut'=>"",
							'ngay'=>date("d"),
							'thang'=>date("m"),
							'nam'=>date("Y"),
							);
							 
						$this->view->currenttime = $time;
						
					}
				}
				else
				{
					if(isset($_GET['step']) && is_numeric($_GET['step']) && $_GET['step']==2)
					{
						
						if(isset($_SESSION['payment_info']) && $_SESSION['payment_info']!=null)
						{
							if(isset($_SESSION['Cart']) && $_SESSION['Cart']!=null)
							{
								
							}
							else
							{
								unset($_SESSION['payment_info']);
								Header("Location: /cart/error");
							}
						}
						else 
						{
							Header("Location: /cart/index?step=1");
						}
						
					}
					else 
					{
						unset($_SESSION['payment_info']);
						Header("Location: /cart/error");
					}
				}
			
			
		} else {
			unset($_SESSION['payment_info']);
			Header("Location: /cart/error");
		}
	}
	public function errorAction(){
		$language = new Language(APPLICATION_PATH . '/modules/user/languages/cart');
			if(isset($_SESSION['language']))
			{
				$language_id = $_SESSION['language'];
				$tbLanguage = new Language_Model_Language();
				$name = $tbLanguage->getNameLanguage($language_id);
				$language->load($name['name']);
			}
			else
				$language->load('Default');		
				
			$languages = $tbLanguage->getAllLanguages();
			$this->view->languages = $languages;
			/*========== End Load Language ==========*/
				
			/*========== Start Get Text ==============*/
			$this->view->error 	= $language->get('error');
	}
}
?>